{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7dfea76e",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "# 修改部分： \n",
    "        1、为每个 code 单元添加了顶栏注释\n",
    "        2、为缺少 docstring 的函数插入了中文模板\n",
    "        3、将 plt.show(); 统一为 plt.show()（去除多余分号）\n",
    "             "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "640009a6",
   "metadata": {},
   "source": [
    "# 异常值的处理方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae217a0b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 1: 导入依赖库、绘图/可视化 ===\n",
    "import numpy as np # 数据处理最重要的模块\n",
    "import pandas as pd # 数据处理最重要的模块\n",
    "import scipy.stats as stats # 统计模块\n",
    "import scipy\n",
    "# import pymysql  # 导入数据库模块\n",
    "\n",
    "from datetime import datetime # 时间模块\n",
    "import statsmodels.formula.api as smf  # OLS regression\n",
    "\n",
    "# import pyreadr # read RDS file\n",
    "\n",
    "from matplotlib import style  # 绘图\n",
    "import matplotlib.pyplot as plt  # 画图模块\n",
    "import matplotlib.dates as mdates  # 绘图\n",
    "\n",
    "\n",
    "from matplotlib.font_manager import FontProperties # 作图中文\n",
    "from pylab import mpl\n",
    "#mpl.rcParams['font.sans-serif'] = ['SimHei']\n",
    "#plt.rcParams['font.family'] = 'Times New Roman'\n",
    "\n",
    "\n",
    "#输出矢量图 渲染矢量图\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'svg'\n",
    "\n",
    "from IPython.core.interactiveshell import InteractiveShell # jupyter运行输出的模块\n",
    "#显示每一个运行结果\n",
    "InteractiveShell.ast_node_interactivity = 'all'\n",
    "\n",
    "#设置行不限制数量\n",
    "#pd.set_option('display.max_rows',None)\n",
    "\n",
    "#设置列不限制数量\n",
    "pd.set_option('display.max_columns', None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d8103ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 2: 读取数据、数据清洗/转换 ===\n",
    "data = pd.read_csv('datasets/000001.csv', low_memory=False)\n",
    "data['Day'] = pd.to_datetime(data['Day'],format='%Y/%m/%d')\n",
    "data.set_index('Day', inplace = True)\n",
    "data.sort_values(by = ['Day'],axis=0, ascending=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed52d193",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 3: 通用计算/执行 ===\n",
    "data_new = data['1995-01':'2024-09'].copy()\n",
    "data_new['Close'] = pd.to_numeric(data_new['Close'])\n",
    "data_new['Preclose'] = pd.to_numeric(data_new['Preclose'])\n",
    "# 计算000001上证指数日收益率 两种：\n",
    "data_new['Raw_return'] = data_new['Close'] / data_new['Preclose'] - 1\n",
    "data_new"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "125d561d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 4: 通用计算/执行 ===\n",
    "Month_data = data_new.resample('ME')['Raw_return'].apply(lambda x: (1+x).prod()-1).to_frame()\n",
    "Month_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2752b86",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 5: 通用计算/执行 ===\n",
    "Quarter_data = data_new.resample('QE')['Raw_return'].apply(lambda x: (1+x).prod()-1).to_frame()\n",
    "Quarter_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28f737be",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 6: 通用计算/执行 ===\n",
    "Year_data = data_new.resample('YE')['Raw_return'].apply(lambda x: (1+x).prod()-1).to_frame()\n",
    "Year_data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c63bc4f3",
   "metadata": {},
   "source": [
    "## 固定比例法\n",
    "\n",
    "这种方法非常容易理解，我们把上下1%的值重新设置,若大于99%分位数的数值，则将其设置为99%分位数值，若低于1%分位数的数值，则将其重新设置为1%分位数值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40910395",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 7: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].max()\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].min()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f3a5c24",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 8: 通用计算/执行 ===\n",
    "Month_data_fix = Month_data['2000-01':'2024-09'].copy()\n",
    "Month_data_fix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e539760e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 9: 通用计算/执行 ===\n",
    "Month_data_fix[Month_data_fix['Raw_return'] > Month_data_fix['Raw_return'].quantile(\n",
    "    0.99)] = Month_data_fix['Raw_return'].quantile(0.99)\n",
    "Month_data_fix[Month_data_fix['Raw_return'] < Month_data_fix['Raw_return'].quantile(\n",
    "    0.01)] = Month_data_fix['Raw_return'].quantile(0.01)\n",
    "Month_data_fix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "991b106d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 10: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].describe().round(8)\n",
    "Month_data_fix['2000-01':'2024-09']['Raw_return'].describe().round(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d709014",
   "metadata": {},
   "source": [
    "## 均值标准差法\n",
    "\n",
    "这种想法的思路来自正态分布,假设$X \\sim N\\left(\\mu, \\sigma^{2}\\right)$，那么\n",
    "\n",
    "\n",
    "$P(|X-\\mu|>k * \\sigma)= \\begin{cases}0.317, & k=1 \\\\ 0.046, & k=2 \\\\ 0.003, & k=3\\end{cases}$\n",
    "\n",
    "通常把**3倍**标准差之外的值都视为异常值，不过要注意的是样本均值和样本标准差都不是稳健统计量，其计算本身受极值的影响就非常大，所以可能会出现一种情况，那就是我们从数据分布图上能非常明显地看到异常点，但按照上面的计算方法，这个异常点可能仍在均值3倍标准差的范围内。因此按照这种方法剔除掉异常值后,需要重新观察数据的分布情况，看是否仍然存在显著异常点,若存在则继续重复上述步骤寻找异常点."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45744641",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 11: 通用计算/执行 ===\n",
    "Month_data_ms = Month_data['2000-01':'2024-09'].copy()\n",
    "\n",
    "Month_data_ms[Month_data_ms['Raw_return'] >= Month_data_ms['Raw_return'].mean() +\n",
    "         3 * Month_data_ms['Raw_return'].std()] = Month_data_ms['Raw_return'].mean(\n",
    "         ) + 3 * Month_data_ms['Raw_return'].std()\n",
    "\n",
    "Month_data_ms[Month_data_ms['Raw_return'] <= Month_data_ms['Raw_return'].mean() -\n",
    "         3 * Month_data_ms['Raw_return'].std()] = Month_data_ms['Raw_return'].mean(\n",
    "         ) - 3 * Month_data_ms['Raw_return'].std()\n",
    "Month_data_ms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "31f97650",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 12: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].describe().round(8)\n",
    "Month_data_ms['2000-01':'2024-09']['Raw_return'].describe().round(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5b0f776",
   "metadata": {},
   "source": [
    "## MAD法\n",
    "\n",
    "**MAD法**是针对均值标准差方法的改进,把均值和标准差替换成稳健统计量，样本均值用样本中位数代替，样本标准差用样本MAD( median absolute deviation)代替：\n",
    "\n",
    "\\begin{aligned}\n",
    "&\\operatorname{md}=\\operatorname{median}\\left(x_{i}, i=1,2, \\cdots, n\\right) \\\\\n",
    "&\\mathrm{MAD}=\\operatorname{mean}\\left(\\left|x_{i}-\\mathrm{md}\\right|, i=1,2, \\cdots, n\\right)\n",
    "\\end{aligned}\n",
    "\n",
    "一般将偏离中位数3倍以上的数据作为异常值，和均值标淮差法相比，其中位数和MAD不受异常值的影响。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a34a2954",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 13: 通用计算/执行 ===\n",
    "Month_data_median = Month_data['2000-01':'2024-09'].copy()\n",
    "\n",
    "median = np.median(Month_data_median['Raw_return'])\n",
    "MAD = np.mean(abs(Month_data_median['Raw_return'] - median))\n",
    "\n",
    "Month_data_median[Month_data_median['Raw_return'] >= 3 * MAD + median] = 3 * MAD + median\n",
    "Month_data_median[Month_data_median['Raw_return'] <= -3 * MAD + median] = -3 * MAD + median\n",
    "\n",
    "Month_data_median"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e859a234",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 14: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].describe().round(8)\n",
    "Month_data_median['2000-01':'2024-09']['Raw_return'].describe().round(8)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c68bc26",
   "metadata": {},
   "source": [
    "# 参数假设检验"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9df63fc0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 15: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3684267a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 16: 绘图/可视化 ===\n",
    "fig, ax = plt.subplots(figsize = (8,4))\n",
    "\n",
    "ax.plot('Raw_return', # 图片数据\n",
    "'.-', # 图片类型,\n",
    "color = 'r', # 图片颜色\n",
    "label = 'Monthly Return', # 图片标签\n",
    "linewidth = 1, # 图片线宽\n",
    "data = Month_data['2000-01':]) # 图片数据来源\n",
    "ax.set_title(\"China's stock market\") # 图片标题\n",
    "ax.set_ylabel('Return') # 图片y轴标签\n",
    "ax.set_xlabel('Year') # 图片x轴标签\n",
    "\n",
    "# 添加一条y=0的参考线\n",
    "plt.axhline(y=0, color='blue', linewidth=2)\n",
    "# plt.axhline(y=0.005546421267857977, color='green', linewidth=2)\n",
    "\n",
    "# 设置x轴的日期显示格式\n",
    "data_format = mdates.DateFormatter('%Y')\n",
    "ax.xaxis.set_major_formatter(data_format)\n",
    "ax.xaxis.set_major_locator(mdates.YearLocator())\n",
    "\n",
    "# 转置x轴的日期显示格式\n",
    "plt.xticks(rotation = 90)\n",
    "\n",
    "# 添加图例\n",
    "plt.legend(loc='upper right',fontsize = 8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17f8182e",
   "metadata": {},
   "source": [
    " 这个均值真的大于0么？"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d206bdb3",
   "metadata": {},
   "source": [
    "## 基本理论\n",
    "\n",
    "为了推断总体的某些性质，我们会提出;总体性质的各种假设。假设检验就是根据样本提供的信息对所提出的假设作出判断的过程。\n",
    "\n",
    "假设检验依据的原理是小概率事件在抽样中不易发生的原理。\n",
    "\n",
    "原假设是我们有怀疑，想要拒绝的假设，记为$H_0$,备择假设是我们拒绝了原假设后得到的结论,记为$H_a$.\n",
    "\n",
    "假设都是关于总体参数的，例如，我们想知道总体均值是否等于某个常数$\\mu_0$，那么原假设是：$H_0: \\mu = \\mu_0$，则备择假设是：$H_a: \\mu \\ne \\mu_0$.\n",
    "\n",
    "上面这种假设，我们称为双尾检验，因为备择假设是双边的。\n",
    "\n",
    "下面两种假设检验称为单尾检验：\n",
    "\n",
    "\\begin{array}{ll}\n",
    "H_{0}: \\mu \\geqslant \\mu_{0} & H_{\\alpha}: \\mu<\\mu_{0} \\\\\n",
    "H_{0}: \\mu \\leqslant \\mu_{0} & H_{\\alpha}: \\mu>\\mu_{0}\n",
    "\\end{array}\n",
    "\n",
    "注意：无论是单尾还是双尾检验，等号永远都在原假设一边，这是用来判断原来假设的唯一标准."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d21d3a80",
   "metadata": {},
   "source": [
    "![111](./images/CLwMG.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15c8b1fd",
   "metadata": {},
   "source": [
    "### 第一类错误和第二类错误\n",
    "\n",
    "我们在做假设检验的时候会犯两种错误，第一，原来假设是正确的而你判断它为错误的; 第二，原来假设是错误的而你判断它为正确的：我们分别称为第一类错误和第二类错误。\n",
    "\n",
    "第一类错误：原来假设是正确的，却拒绝了原来假设;\n",
    "第二类错误：原来假设是错误的.却没有拒绝原来假设。\n",
    "\n",
    "这类似于法官判案时，如果被告是好人，却判他是坏人，这是第一错误(错杀好人或以真为假）。\n",
    "\n",
    "如果被告是坏人，却判他为好人，这是第二类错误(放走坏人或以假为真)。\n",
    "\n",
    "在其他条什不变的前提下，如果要求犯第一类概率越小,那么犯第二类错误的概率就会越大，通俗理解即，当我们要求错杀好人的概率降低。那么往往就会放走坏人。\n",
    "\n",
    "同样的，在其他情况不变的前提下，如果要求犯第二类错误概率越小,那么犯第一类错误的概率站越大，通俗理解即，当我们要求放走坏人的概率降低。那么往就会错杀好人。\n",
    "\n",
    "其他条什不变主要指的是样本量$n$不变，换言之，要想少犯第一类错误的概率和第二类错误的概率，**就要增大样本量$n$**。\n",
    "\n",
    "在假设检验的时候，我们会规定一个允许犯第一类错误的概率，比如5%，这称为显著性水平,记为$ \\alpha $。我们通常只规定犯第一类错误的概率，而不规定犯第二类错误的概率。\n",
    "\n",
    "\n",
    "|     | 原假设正确   | 原假设不正确       |\n",
    "|:-----------:|:-------------:|:-------------:|\n",
    "| 拒绝原假设  | 第一类错误 显著性水平$ \\alpha $ | 判断正确 检验的势 = 1- $p$（第二类错误） |\n",
    "|没有拒绝原假设 |判断正确 |第二类错误|\n",
    "\n",
    "要做假设检验，我们先要计算两样东西：检验统计量和关键值。\n",
    "\n",
    "检验统计量是从样本数据中计算得来的。检验统计量的一般形式为：\n",
    "\n",
    "，检验统计量=(样本统计量一在$H_0$中假设的总体参数值)/样本统计量的标准误\n",
    "\n",
    "关键值是查表得到的。关键值的计算需要知道以下三点：\n",
    "\n",
    "- 检验统计量是什么分布。这决定我们要去查哪张表。\n",
    "- 显著性水平。\n",
    "- 是双尾还是单尾检验。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b22577e",
   "metadata": {},
   "source": [
    "## 单个总体均值的假设检验\n",
    "\n",
    "我们想知道一个总体均值是否等于（或大于等于、小于等于，某个常数人$\\mu_0$，可以使用$Z$检验或$t$检验。双尾和单尾检验的原假设和备择假设如下:\n",
    "\n",
    "\\begin{array}{ll}\n",
    "H_{0}: \\mu=\\mu_{0}, & H_{\\alpha}: \\mu \\neq \\mu_{0} \\\\\n",
    "H_{0}: \\mu \\geqslant \\mu_{0}, & H_{\\alpha}: \\mu<\\mu_{0} \\\\\n",
    "H_{0}: \\mu \\leqslant \\mu_{0}, & H_{\\alpha}: \\mu>\\mu_{0}\n",
    "\\end{array}\n",
    "\n",
    "下表告诉我们什么时候使用 $ Z $  检验, 什么时候使用$ t$   检验 .\n",
    "\n",
    "|     | 正态总体，$n < 30$   |  $ n >= 30 $      |\n",
    "|:-----------:|:-------------:|:-------------:|\n",
    "| 已知总体方差  | $Z$检验 | $Z$检验 |\n",
    "| 未知总体方差 |$t$检验 |$t$检验 或 $Z$检验 |\n",
    "\n",
    "\n",
    "如果已知总体方差，那么Z统计量的公式为\n",
    "$$\n",
    "Z=\\frac{\\bar{x}-\\mu_{0}}{\\sigma \\sqrt{n}}\n",
    "$$\n",
    "\n",
    "其中, $\\bar{x}$ 为样本均值, $\\sigma$ 为总体标准差, $n$ 为样本容量。\n",
    "\n",
    "如果末知总体方差,那么 $Z$ 统计量的公式为\n",
    "$$\n",
    "Z=\\frac{\\bar{x}-\\mu_{0}}{s \\sqrt{n}}\n",
    "$$\n",
    "其中, $\\bar{x}$ 为样本均值, $s$ 为样本标准差\n",
    "$\\left(n>30, s^{2}=\\frac{1}{n} \\sum_{i=1}^{n}\\left(x_{i}-\\bar{x}\\right)^{2}, n<30, s^{2}=\\frac{1}{n-1} \\sum_{i=1}^{n}\\left(x_{i}-\\bar{x}\\right)^{2}\\right), n$ 为样本容量。\n",
    "$t$ 统计量的公式为\n",
    "$$\n",
    "t_{n-1}=\\frac{\\bar{x}-\\mu_{0}}{s \\sqrt{n}}\n",
    "$$\n",
    "其中, $\\bar{x}$ 为样本均值, $s$ 为样本标准差, $n$ 为样本容量。下标$n-1$是$t$分布的自由度，这个对于关键值至关重要。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9f07c5d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 17: 通用计算/执行 ===\n",
    "Month_data['2000-01':'2024-09']['Raw_return'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5003cac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 18: 通用计算/执行 ===\n",
    "stats.ttest_1samp(Month_data['1995-01':'2024-09']['Raw_return'],0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "927e701f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 19: 通用计算/执行 ===\n",
    "stats.ttest_1samp(Month_data['2000-01':'2024-09']['Raw_return'],0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebe57e1d",
   "metadata": {},
   "source": [
    " ## Question\n",
    " 样本的均值和计算的Z值或者是t-value符号是否是一致的？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5257cfb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 20: 通用计算/执行 ===\n",
    "# 学生的分数数79 79 79 79 100\n",
    "# 均值是多少\n",
    "data = [79,79,79,79,100]\n",
    "np.mean(data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "581733ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 21: 通用计算/执行 ===\n",
    "# t.test data\n",
    "stats.ttest_1samp(data,80)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff27d489",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 22: 通用计算/执行 ===\n",
    "style.available"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6209fb07",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 23: 导入依赖库、绘图/可视化 ===\n",
    "import numpy as np  # 数值计算\n",
    "import matplotlib.pyplot as plt  # 绘图\n",
    "import scipy.stats as stats\n",
    "\n",
    "# 设置参数\n",
    "alpha = 0.05  # 显著性水平\n",
    "df = 100  # 自由度，假设样本量为101\n",
    "t_crit = stats.t.ppf(1 - alpha / 2, df)  # 双侧检验临界值\n",
    "\n",
    "# 生成 t 分布的 x 轴数据\n",
    "x = np.linspace(-4, 4, 1000) # 生成 -4 到 4 之间的 1000 个数据\n",
    "y = stats.t.pdf(x, df) # 计算 t 分布的概率密度函数\n",
    "\n",
    "# 绘制 t 分布曲线\n",
    "plt.figure(figsize=(10, 6)) # 设置图形大小\n",
    "plt.style.use('ggplot') # 设置风格\n",
    "plt.plot(x, y, label=f't-distribution (df={df})', color='blue') # 绘制 t 分布曲线\n",
    "\n",
    "# 填充拒绝原假设区域\n",
    "plt.fill_between(x, 0, y, where=(x >= t_crit) | (x <= -t_crit), color='red', alpha=0.7, label='Rejection region')\n",
    "\n",
    "# 标出 t 临界值\n",
    "plt.axvline(t_crit, color='red', linestyle='--', label=f'Critical value = {t_crit:.2f}') # 标出临界值\n",
    "plt.axvline(-t_crit, color='red', linestyle='--') # 标出临界值\n",
    "\n",
    "# 假设计算出的 t 值 (例如 t = 2.1)\n",
    "t_value = 2.1\n",
    "plt.axvline(t_value, color='green', linestyle='-', label=f't-value = {t_value}')\n",
    "\n",
    "# 图形标注\n",
    "plt.title('t-distribution with Rejection Regions and t-value')\n",
    "plt.xlabel('t-value')\n",
    "plt.ylabel('Probability Density')\n",
    "plt.legend()\n",
    "\n",
    "# 显示图形\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd64b8ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 24: 导入依赖库、绘图/可视化、循环/迭代 ===\n",
    "import numpy as np  # 数值计算\n",
    "import matplotlib.pyplot as plt  # 绘图\n",
    "\n",
    "# 设置参数\n",
    "num_trials = 10000  # 总实验次数\n",
    "num_samples = 1000  # 每次实验的样本大小\n",
    "results = []  # 存储每次实验的均值\n",
    "\n",
    "# 模拟实验\n",
    "for _ in range(num_trials):\n",
    "    # 抛掷硬币，0代表正面，1代表反面\n",
    "    samples = np.random.binomial(n=1, p=0.5, size=num_samples) # 二项分布\n",
    "    results.append(np.mean(samples))  # 计算均值并存储\n",
    "\n",
    "# 计算总体均值\n",
    "theoretical_mean = 0.5  # 理论均值（正面概率）\n",
    "\n",
    "# 绘制结果\n",
    "plt.figure(figsize=(10, 6))\n",
    "plt.plot(np.arange(1, num_trials + 1), results, label='Sample Mean', color='blue', alpha=0.5)\n",
    "plt.axhline(y=theoretical_mean, color='red', linestyle='--', label='Theoretical Mean (0.5)')\n",
    "plt.title('Law of Large Numbers: Sample Mean vs. Theoretical Mean')\n",
    "plt.xlabel('Number of Trials')\n",
    "plt.ylabel('Sample Mean')\n",
    "plt.legend()\n",
    "plt.grid(True)\n",
    "plt.ylim(0, 1)  # 限制 y 轴范围\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32843968",
   "metadata": {},
   "outputs": [],
   "source": [
    "# === 单元格 25: 导入依赖库、绘图/可视化、循环/迭代 ===\n",
    "import seaborn as sns  # 统计可视化\n",
    "\n",
    "# 设置参数\n",
    "num_samples = 1000  # 每次抽样的样本大小\n",
    "num_trials = 1000   # 抽样的次数\n",
    "sample_means = []   # 存储样本均值\n",
    "\n",
    "# 从非正态分布（例如均匀分布）中抽样\n",
    "for _ in range(num_trials):\n",
    "    samples = np.random.uniform(low=-1, high=1, size=num_samples)  # 生成均匀分布样本\n",
    "    sample_means.append(np.mean(samples))  # 计算均值并存储\n",
    "\n",
    "# 绘制结果\n",
    "plt.figure(figsize=(12, 6))\n",
    "\n",
    "# 绘制样本均值的分布\n",
    "sns.histplot(sample_means, bins=30, kde=True, color='blue', stat='density', label='Sample Means')\n",
    "\n",
    "# 绘制标准正态分布\n",
    "mu = np.mean(sample_means)\n",
    "sigma = np.std(sample_means)\n",
    "x = np.linspace(mu - 4*sigma, mu + 4*sigma, 100)\n",
    "plt.plot(x, stats.norm.pdf(x, mu, sigma), color='red', linestyle='--', label='Normal Distribution')\n",
    "\n",
    "# 图形标注\n",
    "plt.title('Demonstration of the Central Limit Theorem')\n",
    "plt.xlabel('Sample Means')\n",
    "plt.ylabel('Density')\n",
    "plt.legend()\n",
    "plt.grid(True)\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
